package com.taotao.order.task;

import com.taotao.common.redis.service.RedisService;
import com.taotao.order.constants.OrderConstants;
import com.taotao.product.domain.SkuInventoryQuantity;
import com.taotao.remote.SkuInfoRemoteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @className: SynchronizeInventory
 * @author: ZhangYuQi
 * @date: 2025/2/9 下午11:55
 * @Version: 1.0
 * @description:
 */

@Component
public class SynchronizeInventory {

    @Autowired
    private RedisService redisService;

    @Autowired
    private SkuInfoRemoteService skuInfoRemoteService;

    //定时任务 一分钟执行一次
    @Scheduled(cron = "0 0/1 * * * ?")
    public void synchronizeInventory() {
        System.out.println("同步redis库存信息到mysql");

        //构建远程调用传输对象集合
        List<SkuInventoryQuantity> skuInventoryQuantities = new ArrayList<>();

        //获取所有sku
        Collection<String> keys = redisService.keys(OrderConstants.SKU_INFO+"*");
        for (String key : keys) {
            String[] split = key.split(":");
            String skuId = split[1];
            Integer num = redisService.getCacheObject(key);

            //构建远程调用传输对象
            SkuInventoryQuantity skuInventoryQuantity = new SkuInventoryQuantity();
            skuInventoryQuantity.setSkuId(skuId);
            skuInventoryQuantity.setNum(num);
            //放入集合中
            skuInventoryQuantities.add(skuInventoryQuantity);
        }

        //远程调用 同步库存信息
        skuInfoRemoteService.decrInventory(skuInventoryQuantities);


    }


}
